﻿(function ($) {
    var liClick = 0;
    var wWidth = 0;
    var wHeight = 0;
    var xPos = 0;
    var commentPinned = 1;
    var menuLevel = [];
    var trackView = true;
    var AllPhotos = [];

    $.fn.hilight = function () {
        manageTrackView();

        SetContentHeight();
        $(window).resize(function () { SetContentHeight() });
        $("#header").click(function () { test(); });
        $("#arrowleft").click(function () { arrowLeft(); });
        $("#arrowright").click(function () { arrowRight(); });
        //$("#menu").mouseleave(function () { hidemenu(); });
        $("#showmenu").click(function () { showmenu(); });
        $("#showslide").click(function () { showslide(); });
        $("#slide").mouseleave(function () { slideTransparent(); });
        $("#slide").mouseenter(function () { slideVisible(); });
        $("#prevslide").click(function () { prevSlide(); });
        $("#nextslide").click(function () { nextSlide(); });
        $("#img1").bind('load', function () { fadeTo(); });
        $("#img2").bind('load', function () { fadeTo(); });

        $("#comment").mouseenter(function () { showComment(); });
        $("#comment").mouseleave(function () { hideComment(); });
        $("#pin").click(function () { showMap(); });
        $("#pin2").live('click', function (ev) {
            pinComment();
        });

        $("#btn1").live('click', function (ev) {
            $("#imgHelp").attr('src', "img/Sito1.png");
        });

        $("#btn2").live('click', function (ev) {
            $("#imgHelp").attr('src', "img/Sito2.png");
        });


        $("#help").click(function () { showHelp(); });

        if ($.cookie('commentPinned') != null)
            commentPinned = $.cookie('commentPinned');

        if (commentPinned == 1) {
            $("#comment").attr('showcomment', '1');
            showComment();
        }

        $("#showslide").mouseenter(function () { if ($("#showslide").css('opacity') != 0) $("#showslide").animate({ opacity: 1 }, 250); });
        $("#showslide").mouseleave(function () {
            if ($("#showslide").css('opacity') > 0.3)
                $("#showslide").animate({ opacity: 0.3 }, 250);
        });

        $("#showmenu").mouseenter(function () { $("#showmenu").animate({ opacity: 1 }, 250); });
        $("#showmenu").mouseleave(function () {
            if ($("#showmenu").css('opacity') != 0)
                $("#showmenu").animate({ opacity: 0.5 }, 250);
        });

        $(window).keyup(function (event) {
            // Right 39
            // Left 32
            // Left 37 
            switch (event.which) {
                case 39:
                    nextSlide();
                    break;
                case 37:
                    prevSlide();
                    break;
                case 27:
                    showmenu();
                    break;
                case 34:
                    showslide();
                    break;
                case 33:
                    hideslide();
                    break;
                case 32:
                    ShowHideComment();
                    break;
                //                                default:                          
                //                                    alert(event.which);                          
            }
        });

        $.getJSON("images/images.js", function (json) {
            LoadJson(json);

            var album = getUrlVars()['album'];
            if (typeof album != 'undefined')
                loadAlbum(menuLevel['private'][album]);
            else {
                if (menuLevel['stars'] != null) {
                    loadAlbum(menuLevel['stars']['stars']);
                    $("#titleslide").text("Preferite");
                    $("#titleslide").append("<div id='slideclose'>");
                }
            }
            loadActive();
        });

        $("#slideclose").live('click', function (ev) {
            hideslide();
        });

        $('.menu').live('click', function (ev) {
            if (ev.target != this)
                return;
            toggleMenu(ev);
        });

        $('.sottomenu').live('click', function (ev) {
            hidemenu();
            LoadSlide(ev.target);
        });

        $('#map_close').live('click', function (ev) {
            $("#map_close").animate({ opacity: 0 }, 600, function () { $("#map_close").remove(); });
            $("#map_container").animate({ opacity: 0 }, 600, function () { $("#map_container").remove(); });
            $("#map_background").animate({ opacity: 0 }, 600, function () { $("#map_background").remove(); });
        });

        $('#thumb-list li').live('click', function (ev) {
            setActive($(ev.target).parent());
            var key = $('.isActive').children('img').attr('alt');
            if (trackView)
                $.trackEvent('image', key, 'show', 1);

        });
    };

    $.fn.getDimension = function (img) {
        $("#thumb-list").width($("#thumb-list").width() + $(img).width() + 4);
    }

    function manageTrackView() {
        if (getUrlVars()['TrackView'] != null) {
            if (getUrlVars()['TrackView'] == 'false')
                $.cookie('TrackView', false, { expires: 720 });
            else
                $.cookie('TrackView', null);
        }
        if ($.cookie('TrackView') != null)
            trackView = $.cookie('TrackView');

        if (trackView == true)
            $.trackPage("UA-1528535-1");
    }

    function setActive(elem) {
        $('.isActive').removeClass('isActive');
        $(elem).addClass('isActive');
        loadActive();
    }

    function toggleMenu(ev) {
        $(".menu").each(function () {
            if ($(this).children().css('display') == 'block')
                $(this).children().slideUp();
        });

        if ($(ev.target).children().css('display') == 'block')
            $(ev.target).children().slideUp();
        else
            $(ev.target).children().slideDown();
    };

    function SetContentHeight() {
        if ($("#map_background") != 'undefined') {
            $("#map_background").remove();
            $("#map_container").remove();
            $("#map_close").remove();
        }
        wWidth = $(window).width();
        wHeight = $(window).height();
        $("#content").height($(window).height() - $("#header").height() - 5);
        $("#imgTop").height($("#content").height());
        $("#menu").css('top', $("#content").position().top);
        $("#menu").height($(window).height() - $("#header").height() - 5);
        $("#showslide").css('top', $("body").height() - $("#showslide").height());
        $("#showslide").css('left', ($("body").width() - $("#showslide").width()) / 2);
        $("#slide").css('top', $("body").height() - $("#slide").height());
        $("#progress").css('top', ($("body").height() - $("#progress").height()) / 2);
        $("#progress").css('left', ($("body").width() - $("#progress").width()) / 2);
        $("#comment").css('left', ($("body").width() - $("#comment").width()) / 2);
        centerimage($("#img1"));
        centerimage($("#img2"));
    }

    function centerimage(image) {
        $(image).css("width", "auto").css("height", "auto"); // Remove existing CSS
        $(image).removeAttr("width").removeAttr("height"); // Remove HTML attributes
        var width = $(image).width();    // Current image width
        var height = $(image).height();  // Current image height

        var hProp = wWidth / width;
        var vProp = ($("#content").height() - 7) / height;

        if (hProp > vProp) {
            $(image).css("width", width * vProp); // Set new width
            $(image).css("height", height * vProp);
        }
        else {
            $(image).css("width", width * hProp); // Set new width
            $(image).css("height", height * hProp);
        }

        $(image).css('left', (wWidth - $(image).width()) / 2)
        $(image).css('top', (wHeight - $(image).height() - $("#header").height()) / 2 + $("#header").height())

        if ($(image).attr('isTop') == '1')
            $("#pin").css('left', $(image).position().left + $(image).width() - 25);
    }

    function hidemenu() {
        if (liClick == 1)
            liClick = 0;
        else {
            $("#menu").animate({ opacity: 0, left: -250 }, 500);
            $("#showmenu").animate({ opacity: 0.5 }, 500);
        }
    }

    function showmenu() {
        if ($("#slide").css('opacity') != 0)
            hideslide();
        $("#showmenu").animate({ opacity: 0 }, 500);
        $("#menu").animate({ opacity: 1, left: 0 }, 500);
    }

    function showslide() {
        if ($("#menu").css('opacity') != 0)
            hidemenu();
        $("#showslide").animate({ opacity: 0 }, 500);
        $("#slide").animate({ opacity: 1, height: 130, top: $("body").height() - 130 }, 500);
    }

    function hideslide() {
        if (liClick == 1)
            liClick = 0;
        else {
            $("#slide").animate({ opacity: 0, height: 0, top: $("body").height() }, 500);
            $("#showslide").animate({ opacity: 0.3 }, 500);
        }
    }

    function slideVisible() {
        $("#slide").animate({ opacity: 1 }, 500);
    }

    function slideTransparent() {
        $("#slide").animate({ opacity: 0.3 }, 500);
    }

    function LoadJson(json) {
        $.each(json, function (i, field) {
            AllPhotos[field.filename] = field;

            if (field.events != null && field.events != '') {
                if (typeof menuLevel['events'] == 'undefined')
                    menuLevel['events'] = new Array();
                loadMenuLevel(menuLevel['events'], field.events, field);
            }

            if (field.type != null && field.type != '') {
                if (typeof menuLevel['type'] == 'undefined')
                    menuLevel['type'] = new Array();
                loadMenuLevel(menuLevel['type'], field.type, field);
            }

            if (field.stars != null && field.stars >= 2) {
                if (typeof menuLevel['stars'] == 'undefined')
                    menuLevel['stars'] = new Array();
                loadMenuLevel(menuLevel['stars'], 'stars', field);
            }

            if (field.private != null && field.private != '') {
                if (typeof menuLevel['private'] == 'undefined')
                    menuLevel['private'] = new Array();
                loadMenuLevel(menuLevel['private'], field.private, field);
            }
        });

        $("#master").append("<li id='eventi' class='menu'>" + "Eventi");
        $("#eventi").append("<ul class='slave' style='display:block'>");
        for (key in menuLevel['events'])
            $("#eventi ul").append("<li class='sottomenu'>" + key).attr("menu", "events");

        $("#master").append("<li id='genere' class='menu'>" + "Genere");
        $("#genere").append("<ul class='slave' style='display:none'>");
        for (key in menuLevel['type'])
            $("#genere ul").append("<li class='sottomenu'>" + key).attr("menu", "type");
    }

    function loadMenuLevel(myMenu, menulev1, field) {
        if (typeof myMenu[menulev1] == 'undefined')
            myMenu[menulev1] = new Array();

        myMenu[menulev1].push(field.filename);
    }

    function LoadSlide(albumobject) {
        var album = $(albumobject).text();
        if (trackView)
            $.trackEvent('album', album, 'click', 2);

        $("#titleslide").text(album);
        $("#titleslide").append("<div id='slideclose'>");

        var menulev1 = $(albumobject).parent().attr("menu");
        $("#thumb-list").children("li").remove();
        $("#thumb-list").width(0);
        $("#thumb-list").css("left", 0);
        xPos = 0;

        loadAlbum(menuLevel[menulev1][album]);
        loadActive();
    }

    function loadAlbum(album) {
        var firstTime = 1;

        for (key in album) {
            var img1 = new Image();
            img1.src = "thumbnails\\" + album[key] + ".jpg";
            img1.alt = album[key];

            img1.onload = function () {
                $("#thumb-list").width($("#thumb-list").width() + this.width + 4);
            }

            var myLI = $('<li />');
            myLI.append(img1);
            if (firstTime) {
                firstTime = 0;
                myLI.addClass("isActive");
            }
            $("#thumb-list").append(myLI);
        }
    }

    function loadActive() {
        if ($('.isActive') == null)
            return;
        var key = $('.isActive').children('img').attr('alt');
        if (key == null)
            return;

        loadimage(key);
    }

    function loadimage(keyImage) {
        $("#pin").css('opacity', 0);
        var urlImage = "images\\" + keyImage + ".jpg";
        $("#progress").css({ opacity: 1 }, 10);
        if ($("#img1").attr('isTop') == '1') {
            if ($("#img2").attr('alt') != keyImage)
                $("#img2").attr('src', urlImage).attr('alt', keyImage);
            else
                fadeTo();
        }
        else {
            if ($("#img1").attr('alt') != keyImage)
                $("#img1").attr('src', urlImage).attr('alt', keyImage);
            else
                fadeTo();
        }
    }

    function loadTitleComment(image) {
        var keyImage = $(image).attr('alt');
        if (trackView)
            $.trackEvent('menu', keyImage, 'show', 3);

        var showComm = 0;
        $("#comment").html("");
        if (AllPhotos[keyImage].title != undefined && AllPhotos[keyImage].title != "") {
            $("#comment").append("<span class='title'>" + AllPhotos[keyImage].title + "</span>");
            showComm = 1
        }

        if (AllPhotos[keyImage].comment != undefined && AllPhotos[keyImage].comment != "") {
            if (AllPhotos[keyImage].title != undefined && AllPhotos[keyImage].title != "")
                $("#comment").append("<BR>");
            $("#comment").append("<span class='comment'>" + AllPhotos[keyImage].comment + "</span>");
            showComm = 1
        }

        if (AllPhotos[keyImage].place != undefined && AllPhotos[keyImage].place != "") {
            if ((AllPhotos[keyImage].title != undefined && AllPhotos[keyImage].title != "") || (AllPhotos[keyImage].comment != undefined && AllPhotos[keyImage].comment != ""))
                $("#comment").append("<BR>");
            $("#comment").append("<span class='place'>" + AllPhotos[keyImage].place + "</span>");
            showComm = 1
        }

        if (AllPhotos[keyImage].lat != undefined && AllPhotos[keyImage].lon != undefined) {
            $("#pin").css('top', $(image).position().top + 9);
            $("#pin").css('left', $(image).position().left + $(image).width() - 25);
            $("#pin").css('opacity', 1);
            $("#pin").attr('key', keyImage);
        }
        else {
            $("#pin").css('opacity', 0);
            $("#pin").attr('key', "");
        }

        if (commentPinned == 0) {
            if (showComm) {
                $("#comment").animate({ opacity: 0.1 }, 250);
                $("#comment").attr('showcomment', 1);
            }
            else {
                $("#comment").animate({ opacity: 0 }, 250);
                $("#comment").attr('showcomment', 0);
            }
        }

        $("#comment").append("<div id='pin2'> </div>");
        if (commentPinned == 0)
            $("#pin2").css("background", "url('img/pin_comment.png')");
        else
            $("#pin2").css("background", "url('img/pinned_comment.png')");
    }

    function showComment() {
        if ($("#comment").attr('showcomment') == '1')
            $("#comment").animate({ opacity: 1 }, 250);
    }

    function hideComment() {
        if (commentPinned == 1)
            return;
        if ($("#comment").attr('showcomment') == '1')
            $("#comment").animate({ opacity: 0.1 }, 250);
    }

    function pinComment() {
        if (commentPinned == 0) {
            $("#pin2").css("background", "url('img/pinned_comment.png')");
            commentPinned = 1;
        }
        else {
            $("#pin2").css("background", "url('img/pin_comment.png')");
            commentPinned = 0;
        }
        $.cookie('commentPinned', commentPinned, { expires: 720 });
    }

    function ShowHideComment() {
        pinComment();
        if (commentPinned == 1) {
            $("#comment").animate({ opacity: 1 }, 250);
            $("#comment").attr('showcomment', 1);
        }
        else {
            $("#comment").animate({ opacity: 0.1 }, 250);
            $("#comment").attr('showcomment', 0);
        }
    }

    function fadeTo() {
        $("#progress").css({ opacity: 0 }, 10);
        if ($("#img1").attr('isTop') == '1') {
            centerimage($("#img2"));
            $("#img1").animate({ opacity: 0 }, 950);
            $("#img2").animate({ opacity: 1 }, 750, function () {
                $("#img1").attr('isTop', 0);
                $("#img2").attr('isTop', 1);
                loadTitleComment($("#img2"));
            });
        }
        else {
            centerimage($("#img1"));
            $("#img2").animate({ opacity: 0 }, 950);
            $("#img1").animate({ opacity: 1 }, 750, function () {
                $("#img2").attr('isTop', 0);
                $("#img1").attr('isTop', 1);
                loadTitleComment($("#img1"));
            });
        }
    }
    function arrowLeft() {
        xPos += wWidth;
        if (xPos > 0)
            xPos = 0;
        if (xPos != $("#thumb-list").position().left) {
            $("#thumb-list").animate({ left: xPos }, 500);
        }
    }

    function arrowRight() {
        xPos -= wWidth;
        if (Math.abs(xPos) > $("#thumb-list").width() - wWidth)
            xPos = ($("#thumb-list").width() - wWidth) * -1;
        if (xPos != $("#thumb-list").css("left"))
            $("#thumb-list").animate({ left: xPos }, 500);
    }

    function prevSlide() {
        if ($('.isActive').prev().is("li")) {
            setActive($('.isActive').prev());
        }
    }

    function nextSlide() {
        if ($('.isActive').next().is("li")) {
            setActive($('.isActive').next());
        }
    }

    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

    function showMap() {
        $("body").append("<div id='map_background'>");
        $("#map_background").height($("#content").height());
        $("#map_background").width($("#content").width());
        $("#map_background").css('top', $("#content").position().top);

        $("body").append("<div id='map_container'>");
        var h = $("#map_background").height() * 0.6;
        var w = $("#map_background").width() * 0.6;
        var t = $("#map_background").height() * 0.2;
        var l = $("#map_background").width() * 0.2;
        $("#map_container").css({ 'top': t, 'left': l, 'width': w, 'height': h });

        $("#map_container").bMap({
            mapZoom: 11,
            mapCenter: [AllPhotos[$("#pin").attr('key')].lat, AllPhotos[$("#pin").attr('key')].lon],
            mapLayerbar: "layerBar" //Tell bMap to use a sidebar
        });

        $('#map_container').data('bMap').insertMarkers({
            "name": "Markers",
            "data": [
				{
				    "lat": AllPhotos[$("#pin").attr('key')].lat,
				    "lng": AllPhotos[$("#pin").attr('key')].lon
				}
			]
        });

        $("body").append("<div id='map_close'>");
        //$("#map_close").css('right', $("#map_background").width() * 0.2 + 5);
        $("#map_close").css('right', $("#map_background").width() * 0.2 + 25);
        $("#map_close").css('top', $("#map_background").height() * 0.2 + 40);

        $("#map_background").animate({ opacity: 0.9 }, 500);
        $("#map_container").animate({ opacity: 1 }, 500);
        $("#map_close").animate({ opacity: 1 }, 500);
    }

    function showHelp() {
        if ($("#map_background").is(":visible"))
            return;
        $("body").append("<div id='map_background'>");
        $("#map_background").height($("#content").height());
        $("#map_background").width($("#content").width());
        $("#map_background").css('top', $("#content").position().top);

        $("body").append("<div id='map_container'>");
        var h = $("#map_background").height() * 0.6;
        var w = $("#map_background").width() * 0.6;
        if (h > 562 && w > 800) {
            h = 562;
            w = 800;
        }
        else {
            h = w / 800 * 562;
        }
        var t = $("#map_background").height() * 0.2;
        var l = $("#map_background").width() * 0.2;
        $("#map_container").css({ 'top': t, 'left': l, 'width': w, 'height': h + 24 });
        $("#map_container").append("<img id='imgHelp' src='img/sito1.png'>");
        $("#map_container").append("<img id='btn1' src='img/1.png'>");
        $("#map_container").append("<img id='btn2' src='img/2.png'>");
        $("#imgHelp").height(h);
        $("#imgHelp").width(w);
        $("#btn1").css('left', w / 2 - 6);
        $("#btn2").css('left', w / 2 + 6);

        $("body").append("<div id='map_close'>");
        $("#map_close").css('right', $("#map_background").width() * 0.2 + 25);
        $("#map_close").css('top', $("#map_background").height() * 0.2 + 40);

        $("#map_background").animate({ opacity: 0.9 }, 500);
        $("#map_container").animate({ opacity: 1 }, 500);
        $("#map_close").animate({ opacity: 1 }, 500);
    }
})(jQuery)
